package com.hd.openapi.servies.serviceimpl;

import com.hd.openapi.dao.MenuMapper;
import com.hd.openapi.entity.Menu;
import com.hd.openapi.servies.sermenudata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class sermenudataimpl  implements sermenudata {
    @Autowired
    private MenuMapper a;


    @Override
    public List<Menu> getMenuByUid(Integer id) {
        if (id > 0) {
            //获取用户可以访问的所有的菜单
            List<Menu> all = a.getbymenuid (id);
            List<Menu> collect = all.stream ().filter(x -> x.getParentId() == null).
                    map(x -> findChildren (x,all)).
                    collect(Collectors.toList());
            return collect;
        }
        return null;
    }
    public Menu findChildren(Menu m, List<Menu> all) {
        List<Menu> collect = all.stream().filter(x -> x.getParentId() != null && m.getId().equals(x.getParentId()) && x.getType() != 2).map(x -> findChildren(x, all)).collect(Collectors.toList());
        m.setChildren(collect);
        return m;
    }



    @Override
    public List<Menu> getmenudata(Integer id) {
        //判断id的值
        System.out.println (id);
        if (id>0) {
            //id大于0,根据id获取数据
            List<Menu> getbymenuid = a.getbymenuid (id);
            //设置一个list集合用来保存一级菜单
            List<Menu> yi =new ArrayList<Menu> ();
            for (Menu menu : getbymenuid) {
                //当menu.getParentId ()==null的时候
                if (menu.getParentId ()==null) {
                    //获取一级菜单
                    yi.add (menu);
                }
            }
            for (Menu menu : yi) {
                //保存二级菜单
                List<Menu> er=new ArrayList<Menu> ();
                for (Menu menu1 : getbymenuid) {
                    if (menu1.getParentId ()!=null && menu1.getParentId ().equals (menu.getId ())) {
                                //添加二级菜单
                        er.add (menu1);
                    }
                }
                //把二级菜单添加进一级菜
                menu.setChildren (er);
            }
            return yi;
        }

        return null;
    }
}
